﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

//using System.Windows.Shapes;
using System.Net;
using System.IO;
using System.Collections;
using System.Web;
using Microsoft.Research.DynamicDataDisplay;　//　Core　functionality　
using Microsoft.Research.DynamicDataDisplay.DataSources;　//　EnumerableDataSource　
using Microsoft.Research.DynamicDataDisplay.PointMarkers;　//　CirclePointMarker　
using Microsoft.Research.DynamicDataDisplay.Charts.Navigation;
using System.ComponentModel;
using System.Reflection;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
namespace BallData
{
    /// <summary>
    /// Interaction logic for MatchOddsWnd2.xaml
    /// </summary>
    public partial class MatchOddsWnd2 : Window,INotifyPropertyChanged,WebData
    {
        public MatchData matchdata;
        private MatchOddsData matchoddsdata;
        private String mId;
        public List<ItemListTemplate> itemlist = new List<ItemListTemplate>();
        List<ItemListTemplate> newhistorylist = new List<ItemListTemplate>();
        public Hashtable teaminfohas = new Hashtable();
        public Hashtable adduihash = new Hashtable();

        public Hashtable tabuihash = new Hashtable();
        // 保存获取历史数据状态,防止多次请求
        public Hashtable getdatastate = new Hashtable();

        public Hashtable matchinfotabitem = new Hashtable();
        int resposehistorylist = 0;
        public CompositeDataSource compositeDataSource1;
        public int StartDateTime = 100;
        public int EndDataTime = 1000;
        public String m_StartTimeStr;
        public String StartTimeStr
        {
            get
            {
                return this.m_StartTimeStr;
            }
            set
            {
                if (this.m_StartTimeStr != value)
                {
                    this.m_StartTimeStr = value;
                    OnPropertyChanged("StartTimeStr");
                }
            }
        }
        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion
        public MatchOddsWnd2()
        {
            InitializeComponent();
           
        }
        public void OnWebDataError(String url)
        {
            getdatastate[url] = -1;
        }
        public void OnWebData(byte[] data,String url,Object context)
        {
            if (url.IndexOf("getmatchteaminfo") != -1)
            {
                String response = Encoding.Default.GetString(data);
                TeamMatchInfo teaminfo = TeamMatchInfo.fromJson(response);
                teaminfohas.Add(teaminfo.team_cnname, teaminfo);
                teaminfohas.Add(teaminfo.teamId, teaminfo);

                this.Dispatcher.BeginInvoke((Action)(() =>
                {
                    //this.bet007webbrowser.Navigate(new Uri(teaminfo.taobao_analyurl));
                    if (matchinfotabitem.ContainsKey(teaminfo.team_cnname))
                    {
                        TabItem tb = matchinfotabitem[teaminfo.team_cnname] as TabItem;
                        (tb.Content as WebBrowser).Navigate(new Uri(teaminfo.taobao_analyurl));
                    }
                    else
                    {
                        TabItem tb = new TabItem { Header = teaminfo.team_cnname, Content = new WebBrowser() };
                        (tb.Content as WebBrowser).Navigate(new Uri(teaminfo.taobao_analyurl));
                        this.oddsshape.Items.Add(tb);
                        matchinfotabitem.Add(teaminfo.team_cnname as String, tb);
                    }
                }));
                

            }
            else if (url.IndexOf("oddshistorylist") != -1)
            {
               

                Regex r3 = new Regex("{.*?}");
                String response = Encoding.Default.GetString(data);
                MatchCollection mc = r3.Matches(response);
                for (int i = 0; i < mc.Count; i++)
                {
                    HistoryMatch hismatch = HistoryMatch.fromJson(mc[i].Value);
                    DateTime d = DateTime.Parse(hismatch.starttime);
                    ItemListTemplate history = new ItemListTemplate { name = d.ToString("yyyy-MM-dd") + String.Format("({0} vs {1})",hismatch.host_cnname,hismatch.visit_cnname), his = hismatch };
                    newhistorylist.Add(history);
                    //MatchItem matchitem = (MatchItem)matchdata.MatchList[this.mId];
                    //WebUtil.GetData(String.Format("http://ltfll.gicp.net:8085/matchodds/oddshistory.php?query_cnname={0}&query_date={1}", HttpUtility.UrlEncode(matchitem.t1CnName, Encoding.GetEncoding("gbk")), history.timedata), this);
                }
                resposehistorylist++;

                if (resposehistorylist >= 2)
                {
                    this.Dispatcher.BeginInvoke((Action)(() =>
                {
                    this.historyodds.ItemsSource = newhistorylist; 

                }));
                }
                
                
                
                //Console.WriteLine(his.host_cnname);
                
            }
            else if (url.IndexOf("oddshistory") != -1)
            {
                Console.WriteLine(data.Length);
                HistoryMatch hismatch = context as HistoryMatch;


                String companyodds = Encoding.Default.GetString(ZipHelper.Unzip(data));
                

                //Console.WriteLine(his.host_cnname);
                this.Dispatcher.BeginInvoke((Action)(() =>
                {
                    List<ItemListTemplate> historylistcp = new List<ItemListTemplate>();
                    List<ItemListTemplate> historylist = this.historyodds.ItemsSource as List<ItemListTemplate>;
                    foreach (ItemListTemplate item in historylist)
                    {
                        historylistcp.Add(item);
                    }
                    ItemListTemplate sel = null;
                    foreach (ItemListTemplate item in historylistcp)
                    {
                        if (item.his.mId == hismatch.mId)
                        {
                            sel = item;
                            break;
                        }
                    }
                    if (sel.CompanyList.Count == 0)
                    {
                        Regex r3 = new Regex("{.*?}");
                        MatchCollection mc = r3.Matches(companyodds);

                        Hashtable asiaodds = new Hashtable();
                        Hashtable euproodds = new Hashtable();
                        Hashtable bigsmallodds = new Hashtable();

                        for (int i = 0; i < mc.Count; i++)
                        {
                            //Console.WriteLine(String.Format("for {0},{1}", i, mc.Count));
                            OddsInfo_d getodds = OddsInfo_d.fromJson(mc[i].Value);
                            if (getodds.oType == "a")
                            {
                                Hashtable asiaoddshas = (Hashtable)asiaodds[getodds.cId];
                                
                                if (asiaoddshas == null)
                                {
                                    asiaoddshas = new Hashtable();

                                    asiaodds.Add(getodds.cId, asiaoddshas);
                                }

                                List<OddsInfo_d> oddsinfolist = asiaoddshas[getodds.sId] as List<OddsInfo_d>;

                                if (oddsinfolist == null)
                                {
                                    oddsinfolist = new List<OddsInfo_d>();

                                    asiaoddshas.Add(getodds.sId, oddsinfolist);
                                }

                                oddsinfolist.Add(getodds);
                            }
                            else if (getodds.oType == "e")
                            {
                                Hashtable euprooddshas = (Hashtable)euproodds[getodds.cId];

                                if (euprooddshas == null)
                                {
                                    euprooddshas = new Hashtable();

                                    euproodds.Add(getodds.cId, euprooddshas);
                                }

                                List<OddsInfo_d> oddsinfolist = euprooddshas[getodds.sId] as List<OddsInfo_d>;

                                if (oddsinfolist == null)
                                {
                                    oddsinfolist = new List<OddsInfo_d>();

                                    euprooddshas.Add(getodds.sId, oddsinfolist);
                                }

                                oddsinfolist.Add(getodds);
                            }
                            else if (getodds.oType == "o")
                            {
                                Hashtable bigsmalloddshas = (Hashtable)bigsmallodds[getodds.cId];

                                if (bigsmalloddshas == null)
                                {
                                    bigsmalloddshas = new Hashtable();

                                    bigsmallodds.Add(getodds.cId, bigsmalloddshas);
                                }

                                List<OddsInfo_d> oddsinfolist = bigsmalloddshas[getodds.sId] as List<OddsInfo_d>;

                                if (oddsinfolist == null)
                                {
                                    oddsinfolist = new List<OddsInfo_d>();

                                    bigsmalloddshas.Add(getodds.sId, oddsinfolist);
                                }

                                oddsinfolist.Add(getodds);
                            }
                         
                        }
                        Hashtable oddscount = new Hashtable();

                        String[] matchoddsindex = { "1", "2", "3", "4" };
                        foreach (CompanyItem ci in matchdata.CompanyList.Values)
                        {
                            TreeItemCompany ts = new TreeItemCompany();
                            ts.name = ci.cnName.Trim();
                            
                            String cId = ci.cId;
                            ts.cId = ci.cId;
                            oddscount[ci.cId] = 0;
                            Hashtable asiaoddshas = asiaodds[ci.cId] as Hashtable;
                            if (asiaoddshas != null)
                            {
                                foreach (String index in matchoddsindex)
                                {
                                    List<OddsInfo_d> oddsinfolist = (List<OddsInfo_d>)asiaoddshas[index];
                                    if (oddsinfolist != null)
                                    {
                                        Int32 count = (Int32)oddscount[ci.cId];
                                        count += oddsinfolist.Count;
                                        oddscount[ci.cId] = count;
                                        asiaoddshas = (Hashtable)asiaodds[ci.cId];
                                        if (asiaoddshas.Keys.Count - 1 > 1)
                                            ts.oddstypelist.Add(new TreeItemOddsType { OddsTypeName = "亚盘" + index, OddsTypeIndex = index, OddsType = "a", cId = cId, CompanyName = ts.name, oddsinfolist = oddsinfolist, MatchTime = hismatch.starttime, pitemlisttemplate=sel });
                                        else
                                            ts.oddstypelist.Add(new TreeItemOddsType { OddsTypeName = "亚盘", OddsTypeIndex = "1", OddsType = "a", cId = cId, CompanyName = ts.name, oddsinfolist = oddsinfolist, MatchTime = hismatch.starttime, pitemlisttemplate = sel });

                                    }
                                }
                            }
                           
                            Hashtable euprooddshas = euproodds[ci.cId] as Hashtable;
                            if (euprooddshas != null)
                            {
                                foreach (String index in matchoddsindex)
                                {
                                    List<OddsInfo_d> oddsinfolist = (List<OddsInfo_d>)euprooddshas[index];
                                    if (oddsinfolist != null)
                                    {
                                        Int32 count = (Int32)oddscount[ci.cId];
                                        count += oddsinfolist.Count;
                                        oddscount[ci.cId] = count;
                                        euprooddshas = (Hashtable)euproodds[ci.cId];
                                        if (euprooddshas.Keys.Count - 1 > 1)
                                            ts.oddstypelist.Add(new TreeItemOddsType { OddsTypeName = "欧盘" + index, OddsTypeIndex = index, OddsType = "e", cId = cId, CompanyName = ts.name, oddsinfolist = oddsinfolist, MatchTime = hismatch.starttime, pitemlisttemplate = sel });
                                        else
                                            ts.oddstypelist.Add(new TreeItemOddsType { OddsTypeName = "欧盘", OddsTypeIndex = "1", OddsType = "e", cId = cId, CompanyName = ts.name, oddsinfolist = oddsinfolist, MatchTime = hismatch.starttime, pitemlisttemplate = sel });
                                    }
                                }
                            }
                            
                            Hashtable bigsmalloddshas = bigsmallodds[ci.cId] as Hashtable;
                            if (bigsmalloddshas != null)
                            {
                                foreach (String index in matchoddsindex)
                                {
                                    List<OddsInfo_d> oddsinfolist = (List<OddsInfo_d>)bigsmalloddshas[index];
                                    if (oddsinfolist != null)
                                    {
                                        Int32 count = (Int32)oddscount[ci.cId];
                                        count += oddsinfolist.Count;
                                        oddscount[ci.cId] = count;
                                        bigsmalloddshas = (Hashtable)bigsmallodds[ci.cId];
                                        if (bigsmalloddshas.Keys.Count - 1 > 1)
                                            ts.oddstypelist.Add(new TreeItemOddsType { OddsTypeName = "大小" + index, OddsTypeIndex = index, OddsType = "o", cId = cId, CompanyName = ts.name, oddsinfolist = oddsinfolist, MatchTime = hismatch.starttime, pitemlisttemplate = sel });
                                        else
                                            ts.oddstypelist.Add(new TreeItemOddsType { OddsTypeName = "大小", OddsTypeIndex = "1", OddsType = "o", cId = cId, CompanyName = ts.name, oddsinfolist = oddsinfolist, MatchTime = hismatch.starttime, pitemlisttemplate = sel });
                                    }
                                }
                            }
                            

                            if (ts.oddstypelist.Count > 0)
                            {
                                ts.szoddscount = String.Format("[{0:000}]", (Int32)oddscount[ts.cId]);
                                ts.m_oddscount = (Int32)oddscount[ts.cId];
                                //treecompany.Add(ts);
                                sel.CompanyList.Add(ts);
                            }
                        }

                        sel.CompanyList.Sort(
                           delegate(TreeItemCompany A, TreeItemCompany B)
                           {
                               return B.m_oddscount.CompareTo(A.m_oddscount);
                           }
                           );

                        //historylist = historylistcp;
                        this.historyodds.ItemsSource = historylistcp; 
                        
                    }
                    
                    
                    //ItemListTemplate history = new ItemListTemplate { name = his.starttime };

                    //historylist.Collection.Add(history);
                }));
            }
            getdatastate[url] = 2;
            

        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //this.slider1.DataContext = this;
            this.slider1.Minimum = OddsUntil.ConvertDateTimeInt(DateTime.Now) - 3600 * 24 * 7;
            this.slider1.Maximum = OddsUntil.ConvertDateTimeInt(DateTime.Now) + 3600 * 24 * 7;
            this.DataContext = this;
            StartTimeStr = OddsUntil.ConvertIntDateTime(this.slider1.Minimum).ToString("yyyy-MM-dd hh:mm:ss");

            //this.DataContext = this;
        }
        public void InitData(MatchData matchdata, String mId)
        {

            this.mId = mId;
            this.matchdata = matchdata;

            MatchItem matchitem = (MatchItem)matchdata.Matchs[mId];

            if (matchitem != null)
            {
                StringBuilder strbuilder = new StringBuilder();
                strbuilder.Append("http://odds.gooooal.com/match/");
                strbuilder.Append(Convert.ToInt32(mId) / 1000);
                strbuilder.Append("/");
                strbuilder.Append("m_" + mId + ".match?");
                strbuilder.Append(Convert.ToUInt64(OddsUntil.ConvertDateTimeInt(DateTime.Now)) * 1000);


                HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(strbuilder.ToString());

                httprequest.ContentType = "text/html; charset=utf-8";

                HttpWebResponse response = null;
                try
                {
                    response = (HttpWebResponse)httprequest.GetResponse();
                }
                catch (System.Exception ex)
                {
                    Console.Write(ex.Message);
                    return;
                }



                StreamReader sr = new StreamReader(response.GetResponseStream());
                // 得到赛事数据
                String szmatchdata = sr.ReadToEnd();
                sr.Close();
                response.Close();

                matchoddsdata = new MatchOddsData();

                //分隔大数据域
                String[] domains = szmatchdata.Split(OddsUntil.SplitDomain);

                //处理公共数据域
                String[] publicDomain = domains[0].Split(OddsUntil.SplitColumn);
                matchoddsdata.TimeStamp = Convert.ToUInt64(publicDomain[0], 10);
                matchoddsdata.LoadChg = Convert.ToInt32(publicDomain[1], 10);

                //处理比赛数据
                matchoddsdata.Match = new MatchItem(domains[1]);
                matchoddsdata.MatchDetail = new MatchItemDetail(domains[1]);
                //var companyItem, oddsItem, companyList, oddsList;


                Hashtable oddstyplist = new Hashtable();

                foreach (String type in OddsUntil.oddstype)
                {
                    StringBuilder oddsrequest = new StringBuilder();
                    oddsrequest.Append("http://odds.gooooal.com/match/");
                    oddsrequest.Append(Convert.ToInt32(mId) / 1000);
                    oddsrequest.Append("/" + type + "_" + mId + ".match?ts=");
                    oddsrequest.Append(Convert.ToUInt64(OddsUntil.ConvertDateTimeInt(DateTime.Now)) * 1000);

                    String oddsdata = WebUtil.getDataByUrl(oddsrequest.ToString(),Encoding.UTF8);
                    oddstyplist.Add(type, oddsdata);
                }
               
                foreach(String key in oddstyplist.Keys)
                {
                    //处理公司数据
                    String[] dataDomain = (oddstyplist[key] as String).Split(OddsUntil.SplitDomain);
                    String[] companyDomain = dataDomain[1].Split(OddsUntil.SplitRecord);
                    for (int i = 0; i < companyDomain.Length; i++)
                    {
                        if (companyDomain[i].Length > 5)
                        {
                            CompanyItem companyItem = new CompanyItem(companyDomain[i]);
                            if (!matchoddsdata.CompanyList.ContainsKey(companyItem.cId))
                                matchoddsdata.CompanyList.Add(companyItem.cId, companyItem);
                            
                            
                        }
                    }

                    Hashtable companyList = null;
                    List<OddsInfo_d> oddsList = null;
                    //亚盘,欧盘,大小球
                    // matchoddsdata.AsianData={companyid={"a"=oddslist}
                    // matchoddsdata.EuropeData={companyid={"e"=oddslist}
                    // matchoddsdata.OverUnderData={companyid={"e"=oddslist}

                    String[] oddsDomain = dataDomain[2].Split(OddsUntil.SplitRecord);
                    for (int i = 0; i < oddsDomain.Length; i++)
                    {
                        if (oddsDomain[i].Length > 5)
                        {
                            OddsInfo_d oddsItem = new OddsInfo_d(oddsDomain[i] + OddsUntil.SplitColumn + key + OddsUntil.SplitColumn + mId);

                            if (oddsItem.oType == "a")
                                companyList = (Hashtable)matchoddsdata.AsianData[oddsItem.cId];
                            else if (oddsItem.oType == "e")
                                companyList = (Hashtable)matchoddsdata.EuropeData[oddsItem.cId];
                            else if (oddsItem.oType == "o")
                                companyList = (Hashtable)matchoddsdata.OverUnderData[oddsItem.cId];
                            else
                                continue;
                            if (companyList == null)
                            {
                                companyList = new Hashtable();
                                companyList["cId"] = oddsItem.cId;
                                if (oddsItem.oType == "a")
                                    matchoddsdata.AsianData.Add(oddsItem.cId, companyList);
                                else if (oddsItem.oType == "e")
                                    matchoddsdata.EuropeData.Add(oddsItem.cId, companyList);
                                else if (oddsItem.oType == "o")
                                    matchoddsdata.OverUnderData.Add(oddsItem.cId, companyList);
                            }
                            oddsList = (List<OddsInfo_d>)companyList[oddsItem.sId];
                            if (oddsList == null)
                            {
                                oddsList = new List<OddsInfo_d>();
                                companyList.Add(oddsItem.sId, oddsList);
                            }
                            oddsList.Add(oddsItem);
                        }
                    }
                }
               



            }


            // 保存进入数据库
            #region 
            //matchitem = (MatchItem)matchdata.MatchList[this.mId];

            //if (matchitem != null)
            //{

            //    //StringBuilder sql = new StringBuilder();
            //    //sql.Append("insert matchdata (mId,host_cnname,visit_cnname,starttime,companyodds) ");
            //    StringBuilder companyodds = new StringBuilder();
            //    foreach (CompanyItem ci in matchdata.CompanyList.Values)
            //    {
            //        String cId = ci.cId;

            //        String[] matchoddsindex = { "1", "2", "3", "4" };

            //        Hashtable cdata = (Hashtable)matchoddsdata.AsianData[cId];
            //        if (cdata != null)
            //        {

            //            foreach (String index in matchoddsindex)
            //            {
            //                List<OddsInfo_d> oddsinfolist = (List<OddsInfo_d>)cdata[index];
            //                if (oddsinfolist != null)
            //                {
            //                    foreach (OddsInfo_d odds_d in oddsinfolist)
            //                    {
            //                        companyodds.Append(OddsInfo_d.toJson(odds_d));

            //                    }

            //                }
            //            }
            //        }

            //        cdata = (Hashtable)matchoddsdata.EuropeData[cId];
            //        if (cdata != null)
            //        {
            //            foreach (String index in matchoddsindex)
            //            {
            //                List<OddsInfo_d> oddsinfolist = (List<OddsInfo_d>)cdata[index];
            //                if (oddsinfolist != null)
            //                {
            //                    foreach (OddsInfo_d odds_d in oddsinfolist)
            //                    {
            //                        companyodds.Append(OddsInfo_d.toJson(odds_d));
            //                    }
            //                }
            //            }
            //        }

            //        cdata = (Hashtable)matchoddsdata.OverUnderData[cId];
            //        if (cdata != null)
            //        {
            //            foreach (String index in matchoddsindex)
            //            {
            //                List<OddsInfo_d> oddsinfolist = (List<OddsInfo_d>)cdata[index];
            //                if (oddsinfolist != null)
            //                {
            //                    foreach (OddsInfo_d odds_d in oddsinfolist)
            //                    {
            //                        companyodds.Append(OddsInfo_d.toJson(odds_d));

            //                    }
            //                }
            //            }
            //        }


            //    }



            //    Console.WriteLine(string.Format("datalen:{0}", companyodds.ToString().Length));

            //    byte[] data = System.Text.Encoding.Default.GetBytes(companyodds.ToString());
            //    byte[] zipdata = ZipHelper.Zip(data);


            //    //byte[] unzipdata = ZipHelper.Unzip(zipdata);

            //    //Console.WriteLine(unzipdata);

            //    //Console.WriteLine(string.Format("zipdatalen:{0}", zipdata.Length));

            //    //FileStream fstream =  File.Create("d:\\test.data");

            //    //byte[] writedata = System.Text.Encoding.Default.GetBytes(zipdata);
            //    //fstream.Write(zipdata, 0, zipdata.Length);
            //    //fstream.Close();
            //    String host_cnname = HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding("gbk").GetBytes(matchitem.t1CnName));
            //    String visit_cnname = HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding("gbk").GetBytes(matchitem.t2CnName));

            //    //&companyodds={4}
            //    WebUtil.PostData(String.Format("http://ltfll.gicp.net:8085/matchodds/odds.php?mId={0}&host_cnname={1}&visit_cnname={2}&starttime={3}", matchitem.mId, host_cnname, visit_cnname, matchitem.koTime.ToString("yyyy-MM-dd hh:mm:ss")), zipdata);
                
            


                
               
            //    //ZipHelper.Unzip(data);
            //    //String zipdata = ZipHelper.CompressString(companyodds.ToString());
            //    //String sql = String.Format("insert matchdata (mId,host_cnname,visit_cnname,starttime,companyodds) values ('{0}','{1}','{2}','{3}','{4}')",matchitem.mId,matchitem.t1CnName,matchitem.t2CnName,matchitem.koTime.ToString("yyyy-MM-dd hh:mm:ss"),zipdata);
            //    //DBUtil.insert(sql);
            //    //String sql = "select companyodds from matchdata where id=1";
            //    //String result = DBUtil.getdata(sql);

            //    //String data = ZipHelper.Unzip(result);
            //    //String result = ZipHelper.UnCompressString(zipdata);
            //    //Console.WriteLine(result);
            //}

            #endregion

        }

        public void InitUI()
        {


            MatchItem matchitem = (MatchItem)matchdata.Matchs[this.mId];

            if (matchitem != null)
            {

                this.MatchInfo.Text = matchitem.ToString();


                Bet007_Match tm = Bet007_NetDataHelper.GetMatchDataByName(matchitem.t1CnName,matchitem.t2CnName);

                if(tm == null)
                    tm = Bet007_NetDataHelper.GetMatchDataByEnName(matchitem.t1EnName, matchitem.t2EnName);
                if (tm == null)
                    tm = Bet007_NetDataHelper.GetMatchDataByTrName(matchitem.t1TrName, matchitem.t2TrName);

                if (tm != null)
                {
                    

                    Bet007_AnalysisData analysidata = Bet007_NetDataHelper.bet007_matchdataobj.bet007analydata[tm.mId] as Bet007_AnalysisData;

                    if (analysidata == null)
                    {
                        Bet007_NetDataHelper.GetMatchHistoryData(tm.mId);

                        analysidata = Bet007_NetDataHelper.bet007_matchdataobj.bet007analydata[tm.mId] as Bet007_AnalysisData;
                    }
                    if (analysidata != null)
                    {
                        OddsUntil.analysiss[0].OnAnalysis(tm.mId, analysidata);

                        this.AnalysisInfo.Text += "赔率和概率差值统计:\n";
                        foreach (Hashtable h in OddsUntil.europeoddsfieldsmap)
                        {
                            foreach (String key in h.Keys)
                            {
                                if (key.IndexOf("初始赔率") != -1 || key.IndexOf("初始概率") != -1)
                                {
                                    if (key.IndexOf("初始赔率") != -1)
                                        this.AnalysisInfo.Text += "初始:\n";
                                    List<String> list = h[key] as List<String>;
                                    foreach (String fieldname in list)
                                    {
                                        this.AnalysisInfo.Text += fieldname + ":" + Math.Round((double)analysidata.customanalysisdata[fieldname], 2) + ",";
                                    }
                                }
                                else
                                {
                                    if (key.IndexOf("即时赔率") != -1)
                                        this.AnalysisInfo.Text += "即时:\n";
                                    List<String> list = h[key] as List<String>;
                                    foreach (String fieldname in list)
                                    {
                                        this.AnalysisInfo.Text += fieldname + ":" + Math.Round((double)analysidata.customanalysisdata["即时" + fieldname], 2) + ",";
                                    }
                                }
                            }
                            this.AnalysisInfo.Text += "\n";
                        }
                        
                        this.AnalysisInfo.Text += "\n";
                        this.AnalysisInfo.Text += "赔率和概率上升下降统计:\n";
                        foreach (String filedname in OddsUntil.europeupdownfields)
                        {
                            if (analysidata.customanalysisdata.ContainsKey(filedname))
                                this.AnalysisInfo.Text += filedname + ":" + analysidata.customanalysisdata[filedname] + ",";
                            else
                                this.AnalysisInfo.Text += filedname;
                        }
                        this.AnalysisInfo.Text += "\n";

                        foreach (String hashkey in OddsUntil.team_statefield)
                        {
                            if (analysidata.customanalysisdata.ContainsKey(hashkey))
                            {
                                this.AnalysisInfo.Text+= hashkey ;
                                Hashtable statemap = analysidata.customanalysisdata[hashkey] as Hashtable;
                                foreach (String areakey in statemap.Keys)
                                {
                                    this.AnalysisInfo.Text += areakey + ":" + ((List<String>)statemap[areakey]).Count + ",";
                                }
                                

                            }
                                
                        }
                        this.AnalysisInfo.Text += "\n";

                        foreach (String filter_vs in OddsUntil.filter_close_vss)
                        {
                            if (analysidata.customanalysisdata.ContainsKey(OddsUntil.HOST + filter_vs))
                            {
                                this.AnalysisInfo.Text += OddsUntil.HOST + filter_vs + ":" + analysidata.customanalysisdata[OddsUntil.HOST + filter_vs] + "\n";
                            }
                            
                        }
                        foreach (String filter_vs in OddsUntil.filter_close_vss)
                        {
                            if (analysidata.customanalysisdata.ContainsKey(OddsUntil.VISIT + filter_vs))
                            {
                                this.AnalysisInfo.Text += OddsUntil.VISIT + filter_vs + ":" + analysidata.customanalysisdata[OddsUntil.VISIT + filter_vs] + "\n";
                            }

                        }
                         
                        
                    }
                    
                }
                else
                {
                    Bet007_NetDataHelper.bet007_matchdataobj.Print();
                }
                
                

               
                
                
                this.oddstile.Content =  matchitem.t1CnName + "vs" + matchitem.t2CnName;


                LeagueItem getleagueitem = (LeagueItem)matchdata.LeagueList[matchitem.lId];
                if (getleagueitem != null)
                {
                    this.oddstileleague.Content = getleagueitem.cnName;
                }

                this.oddsmatchheader.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(getleagueitem.color));
            }

            TreeViewItem hostteam = new TreeViewItem();
            hostteam.Header = matchitem.t1CnName;
            hostteam.Selected += new RoutedEventHandler(teaminfo_Selected);
            this.companylist.Items.Add(hostteam);

            TreeViewItem visitteam = new TreeViewItem();
            visitteam.Header = matchitem.t2CnName;
            visitteam.Selected += new RoutedEventHandler(teaminfo_Selected);
            
            this.companylist.Items.Add(visitteam);
            //WebUtil.GetData(String.Format("http://ltfll.gicp.net:8085/matchodds/oddshistory.php?query_cnname={0}&query_date={1}", HttpUtility.UrlEncode(matchitem.t1CnName, Encoding.GetEncoding("gbk")), DateTime.Now.ToString("yyyyMMdd")), this);
            //WebUtil.GetData(String.Format("http://ltfll.gicp.net:8085/matchodds/oddshistorylist.php?query_cnname={0}&query_range_day=15", HttpUtility.UrlEncode(matchitem.t1CnName, Encoding.GetEncoding("utf-8"))), this,null);
            //WebUtil.GetData(String.Format("http://ltfll.gicp.net:8085/matchodds/oddshistorylist.php?query_cnname={0}&query_range_day=15", HttpUtility.UrlEncode(matchitem.t2CnName, Encoding.GetEncoding("utf-8"))), this, null);
            ItemListTemplate curodds = new ItemListTemplate{ name = "当前赔率" };
            //itemlist.Add(curodds);
            //foreach (String company in OddsUntil.companyList.Values)
            // 赔率记录数量
            Hashtable oddscount = new Hashtable();
            String koTime = matchitem.koTime.ToString("yyyyMMdd");
            foreach (CompanyItem ci in matchdata.CompanyList.Values)
            {
                TreeItemCompany ts = new TreeItemCompany();
                //ts.name = company.Split(OddsUntil.SplitColumn)[2];
                ts.name = ci.cnName.Trim();

                oddscount[ci.cId] = 0;
                //String cId = company.Split(OddsUntil.SplitColumn)[0];
                //ts.cId = cId;
                String cId = ci.cId;
                ts.cId = ci.cId;
                String[] matchoddsindex = { "1", "2", "3", "4" };

                // 亚洲盘
                Hashtable cdata = (Hashtable)matchoddsdata.AsianData[cId];
                if (cdata != null)
                {

                    foreach (String index in matchoddsindex)
                    {
                        List<OddsInfo_d> oddsinfolist = (List<OddsInfo_d>)cdata[index];
                        if (oddsinfolist != null)
                        {
                            Int32 count = (Int32)oddscount[ci.cId];
                            count += oddsinfolist.Count;
                            oddscount[ci.cId] = count;

                            if (cdata.Keys.Count - 1 > 1)
                                ts.oddstypelist.Add(new TreeItemOddsType { OddsTypeName = "亚盘" + index, OddsTypeIndex = index, OddsType = "a", cId = cId, CompanyName = ts.name, oddsinfolist = oddsinfolist, MatchTime = koTime });
                            else
                                ts.oddstypelist.Add(new TreeItemOddsType { OddsTypeName = "亚盘", OddsTypeIndex = "1", OddsType = "a", cId = cId, CompanyName = ts.name, oddsinfolist = oddsinfolist, MatchTime = koTime });

                        }
                    }
                }

                // 欧洲盘
                cdata = (Hashtable)matchoddsdata.EuropeData[cId];
                if (cdata != null)
                {
                    foreach (String index in matchoddsindex)
                    {
                        List<OddsInfo_d> oddsinfolist = (List<OddsInfo_d>)cdata[index];
                        if (oddsinfolist != null)
                        {
                            Int32 count = (Int32)oddscount[ci.cId];
                            count += oddsinfolist.Count;
                            oddscount[ci.cId] = count;

                            if (cdata.Keys.Count - 1 > 1)
                                ts.oddstypelist.Add(new TreeItemOddsType { OddsTypeName = "欧盘" + index, OddsTypeIndex = index, OddsType = "e", cId = cId, CompanyName = ts.name, oddsinfolist = oddsinfolist, MatchTime = koTime });
                            else
                                ts.oddstypelist.Add(new TreeItemOddsType { OddsTypeName = "欧盘", OddsTypeIndex = "1", OddsType = "e", cId = cId, CompanyName = ts.name, oddsinfolist = oddsinfolist, MatchTime = koTime });
                        }
                    }
                }

                // 大小球
                cdata = (Hashtable)matchoddsdata.OverUnderData[cId];
                if (cdata != null)
                {
                    foreach (String index in matchoddsindex)
                    {
                        List<OddsInfo_d> oddsinfolist = (List<OddsInfo_d>)cdata[index];
                        if (oddsinfolist != null)
                        {
                            Int32 count = (Int32)oddscount[ci.cId];
                            count += oddsinfolist.Count;
                            oddscount[ci.cId] = count;

                            if (cdata.Keys.Count - 1 > 1)
                                ts.oddstypelist.Add(new TreeItemOddsType { OddsTypeName = "大小" + index, OddsTypeIndex = index, OddsType = "o", cId = cId, CompanyName = ts.name, oddsinfolist = oddsinfolist, MatchTime = koTime });
                            else
                                ts.oddstypelist.Add(new TreeItemOddsType { OddsTypeName = "大小", OddsTypeIndex = "1", OddsType = "o", cId = cId, CompanyName = ts.name, oddsinfolist = oddsinfolist, MatchTime = koTime });
                        }
                    }
                }

                if (ts.oddstypelist.Count > 0)
                {
                    ts.szoddscount = String.Format("[{0:000}]",(Int32)oddscount[ts.cId]);
                    ts.m_oddscount = (Int32)oddscount[ts.cId];
                    //treecompany.Add(ts);
                    curodds.CompanyList.Add(ts);
                }
                

            }

            //foreach (CompanyItem ci in matchdata.CompanyList.Values)
            //{
            //    Boolean bfind = true;
            //    foreach (TreeItemCompany ts in curodds.CompanyList)
            //    {
            //        if(ts.name == ci.cnName)
            //        {
            //            bfind = false;
            //        }
            //    }
            //    if (bfind)
            //    {
            //        TreeItemCompany ts = new TreeItemCompany();
            //        ts.name = ci.cnName;
                    
            //        //treecompany.Add(ts);
            //        curodds.CompanyList.Add(ts);
            //    }
                
            //}

         

            curodds.CompanyList.Sort(
            delegate(TreeItemCompany A, TreeItemCompany B)
            {
                return B.m_oddscount.CompareTo(A.m_oddscount);
            }
            );

            this.curodds.ItemsSource = curodds.CompanyList;

            //this.companylist.ItemsSource = itemlist;

            
            
            //////////////////////////////////////////////////////////////////////////
#region 

            Assembly currentAssembly = typeof(MatchOddsWnd2).Assembly;

            BitmapImage clearicon = new BitmapImage();
            clearicon.BeginInit();
            clearicon.StreamSource = currentAssembly.GetManifestResourceStream("BallData.pic.clearitem.PNG");
            clearicon.EndInit();
            clearicon.Freeze();


            // 追加 清除菜单项目到原有的弹出菜单

            MenuItem clearitem = new MenuItem();
            clearitem.Header = "清空";
            clearitem.Click += OnClearLine;
            clearitem.Icon = new Image { Source = clearicon } ;

            MenuItem hostitem = new MenuItem();
            hostitem.Header = "主队";
            hostitem.Click += OnShowTeamData;

            List<MenuItem> lt = new List<MenuItem>();
            foreach (MenuItem mt in this.plotter_asia.ContextMenu.ItemsSource)
            {
                lt.Add(mt);
            }
            lt.Add(clearitem);
            lt.Add(hostitem);

            this.plotter_asia.ContextMenu = new ContextMenu();
            
            foreach(MenuItem mt in lt)
            {
                this.plotter_asia.ContextMenu.Items.Add(mt);
            }

            //////////////////////////////////////////////////////////////////////////
            clearitem = new MenuItem();
            clearitem.Header = "清空";
            clearitem.Click += OnClearLine;
            clearitem.Icon = new Image { Source = clearicon };

            lt.Clear();
            foreach (MenuItem mt in this.plotter_europe.ContextMenu.ItemsSource)
            {
                lt.Add(mt);
            }
            lt.Add(clearitem);

            this.plotter_europe.ContextMenu = new ContextMenu();
            foreach (MenuItem mt in lt)
            {
                this.plotter_europe.ContextMenu.Items.Add(mt);
            }

            //////////////////////////////////////////////////////////////////////////

            clearitem = new MenuItem();
            clearitem.Header = "清空";
            clearitem.Click += OnClearLine;
            clearitem.Icon = new Image { Source = clearicon };

            hostitem = new MenuItem();
            hostitem.Header = "主队";
            hostitem.Click += OnShowTeamData;

            lt.Clear();
            foreach (MenuItem mt in this.plotter_bigsmall.ContextMenu.ItemsSource)
            {
                lt.Add(mt);
            }
            lt.Add(clearitem);
            lt.Add(hostitem);

            this.plotter_bigsmall.ContextMenu = new ContextMenu();
            foreach (MenuItem mt in lt)
            {
                this.plotter_bigsmall.ContextMenu.Items.Add(mt);
            }
#endregion



            //////////////////////////////////////////////////////////////////////////

           
            //this.plotter_bigsmall.ContextMenu.Items.Add(clearitem);
            //this.plotter_europe.ContextMenu.Items.Add(clearitem);
        }

        void teaminfo_Selected(object sender, RoutedEventArgs e)
        {
            TreeViewItem tv = sender as TreeViewItem;
            String url = String.Format("http://ltfll.gicp.net:8085/matchodds/getmatchteaminfo.php?query_cnname={0}", HttpUtility.UrlEncode(tv.Header as String, Encoding.GetEncoding("utf-8")));
            if (getdatastate[url] == null)
            {
                getdatastate[url] = 1;
                WebUtil.GetData(url, this, null);
            }
            else
            {
                int state = (int)getdatastate[url];

                if (state == 2)
                {
                    TeamMatchInfo teaminfo = this.teaminfohas[tv.Header as String] as TeamMatchInfo;
                    if (matchinfotabitem.ContainsKey(teaminfo.team_cnname))
                    {
                        TabItem tb = matchinfotabitem[teaminfo.team_cnname] as TabItem;
                        (tb.Content as WebBrowser).Navigate(new Uri(teaminfo.taobao_analyurl));
                    }
                    else
                    {
                        TabItem tb = new TabItem { Header = teaminfo.team_cnname, Content = new WebBrowser() };
                        (tb.Content as WebBrowser).Navigate(new Uri(teaminfo.taobao_analyurl));
                        this.oddsshape.Items.Add(tb);
                        matchinfotabitem.Add(teaminfo.team_cnname as String, tb);
                    }

                }
                else if (state == 1)
                {
                    Console.WriteLine("获取数据中....");
                }
                else
                {
                    getdatastate[url] = 1;
                    WebUtil.GetData(url, this, null);

                }


            }
            


        }
        public void OnClearLine(object sender, RoutedEventArgs e)
        {
            TabItem sl = this.oddsshape.SelectedItem as TabItem;

            if (sl != null)
            {
                ChartPlotter cp = sl.Content as ChartPlotter;
                List<LineGraph> rm = new List<LineGraph>();
                List<ElementMarkerPointsGraph> rm2 = new List<ElementMarkerPointsGraph>();
               
                foreach(var p in cp.Children)
                {
                    if (p is LineGraph)
                    {
                        rm.Add(p as LineGraph);
                    }
                    if (p is ElementMarkerPointsGraph)
                    {
                        rm2.Add(p as ElementMarkerPointsGraph);
                    }
 
                }

                foreach (LineGraph l in rm)
                {
                    cp.Children.Remove(l);
                    
                }
                foreach (ElementMarkerPointsGraph d in rm2)
                {
                    cp.Children.Remove(d);

                }

                adduihash.Clear();
                
            }

        }
        
        public void OnShowTeamData(object send,RoutedEventArgs e)
        {


        }

       
        private void companylist_Selected(object sender, RoutedEventArgs e)
        {
            TreeView sl = (TreeView)sender;
            Random d = new Random();

            #region 
   if (sl.SelectedItem is ItemListTemplate)
            {
                ItemListTemplate selitem = sl.SelectedItem as ItemListTemplate;

                String geturl = String.Format("http://ltfll.gicp.net:8085/matchodds/oddshistory.php?query_cnname={0}&query_date={1}", HttpUtility.UrlEncode(selitem.his.host_cnname, Encoding.GetEncoding("gbk")), DateTime.Parse(selitem.his.starttime).ToString("yyyyMMdd"));

                if (getdatastate[geturl] == null)
                {
                    WebUtil.GetData(geturl, this, selitem.his);
                    getdatastate[geturl] = 1;
                }
                else
                {
                    int state = (int)getdatastate[geturl];
                    if (state == 2)
                    {
                        Console.WriteLine("获取数据成功!");
                    }
                    else if (state == -1)
                    {
                        WebUtil.GetData(geturl, this, selitem.his);
                        getdatastate[geturl] = 1;
                    }
                    else
                    {
                        Console.WriteLine("获取数据中....");
                    }
                }
                
                return;
            }
   #endregion

            #region 
            if (sl.SelectedItem is TreeViewItem)
            {

                TreeViewItem tc = sl.SelectedItem as TreeViewItem;

                MatchItem matchitem = (MatchItem)matchdata.Matchs[mId];
                Bet007_Match tm = Bet007_NetDataHelper.GetMatchDataByName(matchitem.t1CnName, matchitem.t2CnName);

                if (tm == null)
                    tm = Bet007_NetDataHelper.GetMatchDataByEnName(matchitem.t1EnName, matchitem.t2EnName);
                if (tm == null)
                    tm = Bet007_NetDataHelper.GetMatchDataByTrName(matchitem.t1TrName, matchitem.t2TrName);
                Uri url = null;
                if (tm != null && tc.Header as String == "情报分析")
                {
                    url = new Uri("http://article.bet007.com/UserWeb/LiveInformation.aspx?ID=" + tm.mId);
                    
                }
                else if (tm != null && tc.Header as String == "亚指")
                {

                    url = new Uri("http://vip.bet007.com/AsianOdds_n.aspx?id=" + tm.mId);
                }
                else if (tm != null && tc.Header as String == "欧指")
                {
                    url = new Uri("http://1x2.bet007.com/oddslist/" + tm.mId  + ".htm");
                    //Bet007_NetDataHelper.GetMatchEuropeOdds(tm.mId);
                }
                else if (tm != null && tc.Header as String == "凯利指数")
                {
                    url = new Uri("http://1x2.bet007.com/kelly.aspx?id=" + tm.mId);
                }
                else if (tm != null && tc.Header as String == "大小")
                {
                    url = new Uri("http://vip.bet007.com/OverDown_n.aspx?id=" + tm.mId + "&team1=" + matchitem.t1TrName + "&team2=" + matchitem.t2TrName);
                }
                else if (tm != null && tc.Header as String == "bet007分析")
                {
                    url = new Uri("http://news.bet007.com/analysis/" + tm.mId  + "cn.htm");

                    Bet007_NetDataHelper.OnGetMatchHistoryData onget = new Bet007_NetDataHelper.OnGetMatchHistoryData(Bet007_NetDataHelper.GetMatchHistoryData);
                    onget.BeginInvoke(tm.mId, Bet007_NetDataHelper.GetMatchHistoryDataOk, onget);

                }
                else if (tc.Header as String == "淘宝彩票")
                {
                    url = new Uri("http://caipiao.taobao.com/lottery/order/lottery_jczq_spf.htm");
                }
                else if (tc.Header as String == "雪缘分析")
                {
                    url = new Uri("http://analysis.gooooal.com/analysis/new/" + matchitem.mId.Substring(0, 4) + "/" + "cn_" + matchitem.mId + ".html");
                }
                else if (tc.Header as String == "比赛分析")
                {
                    
                }
                if(matchinfotabitem.ContainsKey(tc.Header))
                {
                    TabItem tb = matchinfotabitem[tc.Header] as TabItem;
                    (tb.Content as WebBrowser).Navigate(url);
                }
                else
                {
                    TabItem tb = new TabItem { Header = tc.Header, Content = new WebBrowser() };
                    (tb.Content as WebBrowser).Navigate(url);
                    this.oddsshape.Items.Add(tb);
                    matchinfotabitem.Add(tc.Header as String, tb);
                }
                
                return;
            }
           #endregion
            if (sl.SelectedItem is TreeItemOddsType)
            {
                TreeItemOddsType ts = (TreeItemOddsType)sl.SelectedItem;

                if (ts.OddsType == "a" && this.adduihash[ts.MatchTime + ts.CompanyName + ts.OddsType + ts.OddsTypeIndex] == null)
                {
                    this.adduihash[ts.MatchTime + ts.CompanyName + ts.OddsType + ts.OddsTypeIndex] = 1;

                    List<OddsInfo_d> filter = Filter(ts.oddsinfolist);

                    if (filter.Count == 0)
                    {
                        filter = ts.oddsinfolist;
                    }

                    #region 
                    int oddschangecount = 0, oddsvscount = 0, oddsnormalcount = 0;
                    double hostupcount = 0, hostdowncount = 0;
                    double visitupcount = 0, visitdowncount = 0;
                    for (int i = 0; i < filter.Count; i++)
                    {

                        if (i + 1 < filter.Count)
                        {
                            OddsInfo_d curodds = filter[i] as OddsInfo_d;
                            OddsInfo_d nextodds = filter[i + 1] as OddsInfo_d;
                            if (curodds != null && nextodds != null)
                            {
                                if (Math.Abs(Convert.ToDouble(nextodds.host)) > Math.Abs(Convert.ToDouble(curodds.host)))
                                {
                                    hostupcount += Math.Abs(Convert.ToDouble(nextodds.host)) - Math.Abs(Convert.ToDouble(curodds.host));
                                }
                                else
                                {
                                    hostdowncount += Math.Abs(Convert.ToDouble(curodds.host)) - Math.Abs(Convert.ToDouble(nextodds.host));
                                }

                                if (Math.Abs(Convert.ToDouble(nextodds.visit)) > Math.Abs(Convert.ToDouble(curodds.visit)))
                                {
                                    visitupcount += Math.Abs(Convert.ToDouble(nextodds.visit)) - Math.Abs(Convert.ToDouble(curodds.visit));
                                }
                                else
                                {
                                    visitdowncount += Math.Abs(Convert.ToDouble(curodds.visit)) - Math.Abs(Convert.ToDouble(nextodds.visit));
                                }

                                if (Math.Abs(Convert.ToDouble(curodds.host) - Convert.ToDouble(nextodds.host)) > 0.1)
                                {
                                    if (curodds.vnname != nextodds.vnname)
                                    {
                                        oddsvscount++;
                                    }

                                    oddschangecount++;


                                }
                                else if (curodds.vnname != nextodds.vnname)
                                {

                                    oddsvscount++;
                                }
                                else
                                {
                                    oddsnormalcount++;
                                }
                            }

                        }
                    }
                    String oddsallinfo = String.Format("波峰:{0},盘口:{1},普通:{2}\n上升:{3},下降:{4}", oddschangecount, oddsvscount, oddsnormalcount, hostupcount, hostdowncount);
                    
                    MatchItem matchitem = (MatchItem)matchdata.Matchs[mId];
                    String hostname = ts.pitemlisttemplate==null?matchitem.t1CnName:ts.pitemlisttemplate.his.host_cnname;
                    String visitname = ts.pitemlisttemplate == null ? matchitem.t2CnName : ts.pitemlisttemplate.his.visit_cnname;
                    EnumerableDataSource<OddsInfo_d> hostdataSource = new EnumerableDataSource<OddsInfo_d>(filter);
                    hostdataSource.SetXMapping(x => dateAxis.ConvertToDouble(x.chgTime));
                    hostdataSource.SetYMapping(y => Convert.ToDouble(y.host));
                    hostdataSource.AddMapping(ShapeElementPointMarker.ToolTipTextProperty, y => String.Format("{0}:{1},{2},{3}", ts.CompanyName, y.host, y.vnname, hostname));
                    EnumerableDataSource<OddsInfo_d> vistdataSource = new EnumerableDataSource<OddsInfo_d>(filter);
                    vistdataSource.SetXMapping(x => dateAxis.ConvertToDouble(x.chgTime));
                    vistdataSource.SetYMapping(y => Convert.ToDouble(y.visit));
                    vistdataSource.AddMapping(ShapeElementPointMarker.ToolTipTextProperty, y => String.Format("{0}:{1},{2},{3}", ts.CompanyName, y.visit, y.vnname, visitname));
                    #endregion

                    Color hostcolor = Color.FromRgb(Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)));

                    
                    this.plotter_asia.AddLineGraph(
                            hostdataSource,
                            new Pen(new SolidColorBrush(hostcolor), 5),
                            new CircleElementPointMarker
                            {
                                Size = 10,
                                Brush = Brushes.Red,
                                Fill = Brushes.Orange
                            },
                            new PenDescription(ts.OddsTypeName + ts.OddsTypeIndex + "(主队)" + ts.CompanyName + "," + hostname + "\n" + oddsallinfo)
                        );

                    
                    //this.plotter_asia.AddLineGraph(hostdataSource, hostcolor, 5, ts.OddsTypeName + ts.OddsTypeIndex + "(主队)" + ts.CompanyName);
                    //public static LineGraph AddLineGraph(this Plotter2D plotter, IPointDataSource pointSource, Pen linePen, Description description);



                    Color visitcolor = Color.FromRgb(Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)));
                    //this.plotter_asia.AddLineGraph(vistdataSource, visitcolor, 2, ts.OddsTypeName + ts.OddsTypeIndex + "(客队)" + ts.CompanyName);
                    oddsallinfo = String.Format("波峰:{0},盘口:{1},普通:{2}\n上升:{3},下降:{4}", oddschangecount, oddsvscount, oddsnormalcount, visitupcount, visitdowncount);
                    this.plotter_asia.AddLineGraph(
                            vistdataSource,
                            new Pen(new SolidColorBrush(visitcolor), 2),
                            new CircleElementPointMarker
                            {
                                Size = 10,
                                Brush = Brushes.Blue,
                                Fill = Brushes.Chocolate
                            },
                            new PenDescription(ts.OddsTypeName + ts.OddsTypeIndex + "(客队)" + ts.CompanyName + "," + visitname + "\n" + oddsallinfo)
                        );

                    
                }

                if (ts.OddsType == "e" && this.adduihash[ts.MatchTime + ts.CompanyName + ts.OddsType + ts.OddsTypeIndex] == null)
                {
                    this.adduihash[ts.MatchTime + ts.CompanyName + ts.OddsType + ts.OddsTypeIndex] = 1;
                    List<OddsInfo_d> oddsinfolist = Filter(ts.oddsinfolist);

                    EnumerableDataSource<OddsInfo_d> hostdataSource = new EnumerableDataSource<OddsInfo_d>(oddsinfolist);
                    hostdataSource.SetXMapping(x => dateAxis_e.ConvertToDouble(x.chgTime));
                    hostdataSource.SetYMapping(y => Convert.ToDouble(y.host));
                    hostdataSource.AddMapping(ShapeElementPointMarker.ToolTipTextProperty, y => String.Format("{0}:{1}", ts.CompanyName, y.host));

                    EnumerableDataSource<OddsInfo_d> vistdataSource = new EnumerableDataSource<OddsInfo_d>(oddsinfolist);
                    vistdataSource.SetXMapping(x => dateAxis_e.ConvertToDouble(x.chgTime));
                    vistdataSource.SetYMapping(y => Convert.ToDouble(y.visit));
                    vistdataSource.AddMapping(ShapeElementPointMarker.ToolTipTextProperty, y => String.Format("{0}:{1}", ts.CompanyName, y.visit));

                    EnumerableDataSource<OddsInfo_d> vsdataSource = new EnumerableDataSource<OddsInfo_d>(oddsinfolist);
                    vsdataSource.SetXMapping(x => dateAxis_e.ConvertToDouble(x.chgTime));
                    vsdataSource.SetYMapping(y => Convert.ToDouble(y.vs));
                    vsdataSource.AddMapping(ShapeElementPointMarker.ToolTipTextProperty, y => String.Format("{0}:{1}", ts.CompanyName, y.vs));

                    this.plotter_europe.Children.Add(new CursorCoordinateGraph());
                    Color hostcolor = Color.FromRgb(Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)));
                    //this.plotter_europe.AddLineGraph(hostdataSource, hostcolor, 5, ts.OddsTypeName + ts.OddsTypeIndex  + "(主队)" + ts.CompanyName);
                    this.plotter_europe.AddLineGraph(
                            hostdataSource,
                            new Pen(new SolidColorBrush(hostcolor), 5),
                            new CircleElementPointMarker
                            {
                                Size = 10,
                                Brush = Brushes.Red,
                                Fill = Brushes.Orange
                            },
                            new PenDescription(ts.OddsTypeName + ts.OddsTypeIndex + "(主队)" + ts.CompanyName)
                        );

                    Color visitcolor = Color.FromRgb(Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)));
                    //this.plotter_europe.AddLineGraph(vistdataSource, visitcolor, 2, ts.OddsTypeName + ts.OddsTypeIndex + "(客队)" + ts.CompanyName);
                    this.plotter_europe.AddLineGraph(
                            vistdataSource,
                            new Pen(new SolidColorBrush(visitcolor), 2),
                            new CircleElementPointMarker
                            {
                                Size = 10,
                                Brush = Brushes.Blue,
                                Fill = Brushes.Chocolate
                            },
                            new PenDescription(ts.OddsTypeName + ts.OddsTypeIndex + "(客队)" + ts.CompanyName)
                        );

                    Color vscolor = Color.FromRgb(Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)));
                    //this.plotter_europe.AddLineGraph(vsdataSource, vscolor, 2, ts.OddsTypeName + ts.OddsTypeIndex + "(vs)" + ts.CompanyName);
                    this.plotter_europe.AddLineGraph(
                            vsdataSource,
                            new Pen(new SolidColorBrush(vscolor), 2),
                            new CircleElementPointMarker
                            {
                                Size = 10,
                                Brush = Brushes.ForestGreen,
                                Fill = Brushes.GreenYellow
                            },
                            new PenDescription(ts.OddsTypeName + ts.OddsTypeIndex + "(客队)" + ts.CompanyName)
                        );


                }
                if (ts.OddsType == "o" && this.adduihash[ts.MatchTime + ts.CompanyName + ts.OddsType + ts.OddsTypeIndex] == null)
                {
                    this.adduihash[ts.MatchTime + ts.CompanyName + ts.OddsType + ts.OddsTypeIndex] = 1;
                    List<OddsInfo_d> oddsinfolist = Filter(ts.oddsinfolist);

                    EnumerableDataSource<OddsInfo_d> hostdataSource = new EnumerableDataSource<OddsInfo_d>(oddsinfolist);
                    hostdataSource.SetXMapping(x => dateAxis_o.ConvertToDouble(x.chgTime));
                    hostdataSource.SetYMapping(y => Convert.ToDouble(y.host));
                    hostdataSource.AddMapping(ShapeElementPointMarker.ToolTipTextProperty, y => String.Format("{0}:{1},盘口:{2}", ts.CompanyName, y.host, y.vnname));

                    EnumerableDataSource<OddsInfo_d> vistdataSource = new EnumerableDataSource<OddsInfo_d>(oddsinfolist);
                    vistdataSource.SetXMapping(x => dateAxis_o.ConvertToDouble(x.chgTime));
                    vistdataSource.SetYMapping(y => Convert.ToDouble(y.visit));
                    vistdataSource.AddMapping(ShapeElementPointMarker.ToolTipTextProperty, y => String.Format("{0}:{1},盘口:{2}", ts.CompanyName, y.visit, y.vnname));

                    this.plotter_bigsmall.Children.Add(new CursorCoordinateGraph());

                    Color hostcolor = Color.FromRgb(Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)));
                    //this.plotter_bigsmall.AddLineGraph(hostdataSource, hostcolor, 5, ts.OddsTypeName + ts.OddsTypeIndex + "(主队)" + ts.CompanyName);
                    this.plotter_bigsmall.AddLineGraph(
                            hostdataSource,
                            new Pen(new SolidColorBrush(hostcolor), 5),
                            new CircleElementPointMarker
                            {
                                Size = 10,
                                Brush = Brushes.Red,
                                Fill = Brushes.Orange
                            },
                            new PenDescription(ts.OddsTypeName + ts.OddsTypeIndex + "(主队)" + ts.CompanyName)
                        );
                    Color visitcolor = Color.FromRgb(Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)), Convert.ToByte(d.Next(255)));
                    //this.plotter_bigsmall.AddLineGraph(vistdataSource, visitcolor, 2, ts.OddsTypeName + ts.OddsTypeIndex + "(客队)" + ts.CompanyName);
                    this.plotter_bigsmall.AddLineGraph(
                            vistdataSource,
                            new Pen(new SolidColorBrush(visitcolor), 2),
                            new CircleElementPointMarker
                            {
                                Size = 10,
                                Brush = Brushes.Blue,
                                Fill = Brushes.Chocolate
                            },
                            new PenDescription(ts.OddsTypeName + ts.OddsTypeIndex + "(客队)" + ts.CompanyName)
                        );


                }
                
                //////////////////////////////////////////////////////////////////////////
                // 列出数据信息
               
                if (ts.OddsType == "a")
                {
                    String title = "亚盘" + ts.OddsTypeIndex + "(" + ts.CompanyName + ts.MatchTime + ")";
                    List<OddsInfo_d> oddsinfolist = ts.oddsinfolist;

                    if (oddsinfolist != null && tabuihash[title] == null)
                    {
                        TabItem tb = new TabItem();

                        tabuihash[title] = 1;

                        tb.Header = title;

                        ListView listview = new ListView();

                        GridView asiaview = new GridView();

                        asiaview.Columns.Add(new GridViewColumn { Header = "主队帖水", DisplayMemberBinding = new Binding("host"), Width = 80 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "盘口", DisplayMemberBinding = new Binding("vnname"), Width = 120 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "客队贴水", DisplayMemberBinding = new Binding("visit"), Width = 80 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "更新时间", DisplayMemberBinding = new Binding("updatetime"), Width = 180 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "水位", DisplayMemberBinding = new Binding("allodds"), Width = 80 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "利润", DisplayMemberBinding = new Binding("getmoneycent"), Width = 80 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "备注", DisplayMemberBinding = new Binding("period"), Width = 80 });

                        oddsinfolist[0].period = "当前赔率";

                        listview.View = asiaview;

                        tb.Content = listview;
                        listview.ItemsSource = oddsinfolist;

                        this.oddsdata.Items.Add(tb);


                    }
                    
                }
                if (ts.OddsType == "e")
                {
                    String title = "欧盘" + ts.OddsTypeIndex + "(" + ts.CompanyName + ts.MatchTime + ")";
                    List<OddsInfo_d> oddsinfolist = (List<OddsInfo_d>)ts.oddsinfolist;

                    if (oddsinfolist != null && tabuihash[title] == null)
                    {
                        tabuihash[title] = 1;

                        TabItem tb = new TabItem();

                        tb.Header = title;


                        ListView listview = new ListView();

                        GridView asiaview = new GridView();


                        asiaview.Columns.Add(new GridViewColumn { Header = "赔率", DisplayMemberBinding = new Binding("oddsdata1"), Width = 180 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "返还率", DisplayMemberBinding = new Binding("oddsdata2"), Width = 80 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "概率", DisplayMemberBinding = new Binding("oddsdata3"), Width = 180 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "更新时间", DisplayMemberBinding = new Binding("updatetime"), Width = 180 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "备注", DisplayMemberBinding = new Binding("period"), Width = 80 });

                        oddsinfolist[0].period = "当前赔率";

                        listview.View = asiaview;

                        tb.Content = listview;
                        listview.ItemsSource = oddsinfolist;

                        this.oddsdata.Items.Add(tb);

                    }
                   
                }
                if (ts.OddsType == "o")
                {
                    String title = "大小" + ts.OddsTypeIndex + "(" + ts.CompanyName + ts.MatchTime + ")";
                    List<OddsInfo_d> oddsinfolist = (List<OddsInfo_d>)ts.oddsinfolist;

                    if (oddsinfolist != null && tabuihash[title] == null)
                    {
                        tabuihash[title] = 1;

                        TabItem tb = new TabItem();

                        tb.Header = title;


                        ListView listview = new ListView();

                        GridView asiaview = new GridView();


                        asiaview.Columns.Add(new GridViewColumn { Header = "大球贴水", DisplayMemberBinding = new Binding("host"), Width = 80 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "盘口", DisplayMemberBinding = new Binding("vnname"), Width = 120 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "小球贴水", DisplayMemberBinding = new Binding("visit"), Width = 80 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "更新时间", DisplayMemberBinding = new Binding("updatetime"), Width = 180 });
                        asiaview.Columns.Add(new GridViewColumn { Header = "备注", DisplayMemberBinding = new Binding("period"), Width = 80 });

                        oddsinfolist[0].period = "当前赔率";

                        listview.View = asiaview;

                        tb.Content = listview;
                        listview.ItemsSource = oddsinfolist;

                        this.oddsdata.Items.Add(tb);


                    }

                   
                }

                
            }
            

        }

       

        private void valuechange(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            StartTimeStr  = OddsUntil.ConvertIntDateTime(e.NewValue).ToString("yyyy-MM-dd hh:mm:ss");
          
        }

        public List<OddsInfo_d> Filter(List<OddsInfo_d> oddslist)
        {
            
            DateTime starttime = DateTime.Parse(this.StartTimeStr);

            List<OddsInfo_d> l = new List<OddsInfo_d>();

            foreach (OddsInfo_d d in oddslist)
            {
                if (d.chgTime > starttime)
                {
                    l.Add(d);
                }
            }

            return l;
        }
    }
   
    public class TreeItemOddsType
    {
        public String OddsTypeName { get; set; }
        public String OddsTypeIndex { get; set; }
        public String OddsType { get; set; }
        public String cId { get; set; }
        public String CompanyName { get; set; }
        public String MatchTime { get; set; }
        public List<OddsInfo_d> oddsinfolist { get; set; }
        public ItemListTemplate pitemlisttemplate { get; set; }

    }
    public class TreeItemCompany
    {
        public String name { get; set; }
        public String cId { get; set; }
        public String szoddscount{get;set;}
        public int m_oddscount{get;set;}
        public List<TreeItemOddsType> oddstypelist { get; set; }
        public TreeItemCompany()
        {
            m_oddscount = 0;
            oddstypelist = new List<TreeItemOddsType>();
        }
       
    }

    public class ItemListTemplate
    {
        public String name { get; set; }
        public HistoryMatch his { get; set; }
        public List<TreeItemCompany> m_companyList = new List<TreeItemCompany>();
        public List<TreeItemCompany> CompanyList
        {
            get { return m_companyList; }
            set { m_companyList = value; }
        }
    }
    public class HistoryOdds
    {
        public String mId { get; set; }
        public String starttime { get; set; }
        public String host_cnname { get; set; }
        public String visit_cnname { get; set; }
        public String companyodds { get; set; }

        public static HistoryOdds fromJson(String jsondata)
        {
            HistoryOdds historyoddsinfo = JsonConvert.DeserializeObject<HistoryOdds>(jsondata);
            historyoddsinfo.host_cnname = System.Text.Encoding.Default.GetString(Convert.FromBase64String(historyoddsinfo.host_cnname));
            historyoddsinfo.visit_cnname = System.Text.Encoding.Default.GetString(Convert.FromBase64String(historyoddsinfo.visit_cnname));
            //Console.WriteLine(historyoddsinfo.companyodds);
            //Console.WriteLine(String.Format("server data:{0}",historyoddsinfo.companyodds.Length));
            byte[] base64data = Convert.FromBase64String(historyoddsinfo.companyodds);
            historyoddsinfo.companyodds = Encoding.Default.GetString(ZipHelper.Unzip(base64data));
            return historyoddsinfo;
        }
        public static String toJson(HistoryOdds his)
        {
            String jsondata = JsonConvert.SerializeObject(his);

            return jsondata;

        }

    }
    public class HistoryMatch
    {
        public String mId { get; set; }
        public String starttime { get; set; }
        public String host_cnname { get; set; }
        public String visit_cnname { get; set; }
        public static HistoryMatch fromJson(String jsondata)
        {
            HistoryMatch historyoddsinfo = JsonConvert.DeserializeObject<HistoryMatch>(jsondata);
            historyoddsinfo.host_cnname = System.Text.Encoding.GetEncoding("utf-8").GetString(Convert.FromBase64String(historyoddsinfo.host_cnname));
            historyoddsinfo.visit_cnname = System.Text.Encoding.GetEncoding("utf-8").GetString(Convert.FromBase64String(historyoddsinfo.visit_cnname));

            return historyoddsinfo;
        }
        public static String toJson(HistoryMatch his)
        {
            String jsondata = JsonConvert.SerializeObject(his);

            return jsondata;

        }
    }
    public class TeamMatchInfo
    {
        public String team_cnname { get; set; }
        public String taobao_analyurl { get; set; }
        public String teamId { get; set; }
        public static TeamMatchInfo fromJson(String jsondata)
        {

            TeamMatchInfo teammatchinfo = JsonConvert.DeserializeObject<TeamMatchInfo>(jsondata);
            teammatchinfo.team_cnname = System.Text.Encoding.GetEncoding("utf-8").GetString(Convert.FromBase64String(teammatchinfo.team_cnname));

            return teammatchinfo;
        }
    }


}
